const app = getApp()
const baseUrl = app.globalData.baseURL
const request = (url,method='GET',options={})=>{
    return new Promise((resolve, reject) => {
        // 微信开发中模拟 PATCH方法
        if (method == 'PATCH'){
            method = 'POST'
            options= {
                ...options,
                data:{
                    ...options.data,
                    'method':'PATCH'
                }
            }
        }
        wx.showLoading()
        wx.request({
            url:baseUrl + url,
            method:method,
            data: options.data,
            header: {
               ...options.header,
                Authorization:'Bearer ' + (wx.getStorageSync('access_token') || '')
            },
            timeout:15000,
            // 成功返回的信息
            success (res) {
                if (res.statusCode < 400){
                    resolve(res.data)
                } else {
                    let msg = '请求出错'

                    if (res.statusCode === 400){
                        msg = res.data.message
                    } else if (res.statusCode === 401){
                        // 进行登录的时候验证未通过
                        if (url == '/api/auth/login'){
                            msg = '认证失败'
                        }else {
                            msg = '请登录'
                            // 清除过期的token 以及 用户信息
                            wx.removeStorageSync('access_token')
                            wx.removeStorageSync('userinfo')
                            wx.redirectTo({
                                url:'/pages/login/login'
                            })
                        }

                    }else if (res.statusCode === 404){
                        msg = '请求地址出错'
                    }else if (res.statusCode === 422){
                        msg = res.data.errors[Object.keys(res.data.errors)[0]][0]
                    }


                    wx.showToast({
                        title:msg,
                        icon:'error',
                        duration:2000
                    })
                }

            },
            // 失败返回的信息
            fail(res){
                wx.showToast({
                    title:'网络错误',
                    icon:'error',
                    duration:2000
                })
                console.log(res);
            },
            //不管成功或失败都会返回的信息
            complete(){
                wx.hideLoading()
            }
        })
    })
}

const e = {
    request,
    get(url,options){
        return  request(url,'GET',options)
    },
    post(url,options){
        return  request(url,'POST',options)
    },
    put(url,options){
        return  request(url,'PUT',options)
    },
    delete(url,options){
        return  request(url,'DELETE',options)
    },
    patch(url,options){
        return  request(url,'PATCH',options)
    },
}

module.exports = e